import { Node } from "cc";

export namespace WanderList {

    /**
     * 列表包装类
     */
    export class Data {
        private _extra: any;
        private _origin: any;
        private _selected: boolean = false;
        private _index: number = 0;

        constructor(index: number, data: any, extra?: any) {
            this._extra = extra;
            this._origin = data;
            this._index = index;
        }

        public get extra(): any { return this._extra; }

        public get index(): number { return this._index; }

        public set origin(d: any) { this._origin = d; }
        public get origin(): any { return this._origin; }

        public set selected(b: boolean) { this._selected = b; }
        public get selected(): boolean { return this._selected; }
    }

    /**
     * 列表包装函数
     * 排序、从对象变为列表，应当在外部操作
     * @param arrSource 源数据
     * @param condFunc 过滤函数
     * @param extraFunc 将原数据添加额外数据
     * @returns
     */
    export function Wrap<T>(arrSource: T[], condFunc?: (data: T) => boolean, extraFunc?: (data: T) => any): Data[] {
        if (!arrSource) return [];

        let list: Data[] = [];
        for (let v of arrSource) {
            let pass = true;
            if (condFunc) {
                pass = condFunc(v);
            }
            if (!pass) continue;

            let index = list.length;
            let extra = void 0;
            if (extraFunc) {
                extra = extraFunc(v);
            }
            let data = new Data(index, v, extra);
            list.push(data);
        }
        return list;
    }

    /**
     *
     * @param arrSource 源数据
     * @param childCount 孩子数量
     * @param condFunc 过滤函数
     * @param extraFunc 将原数据添加额外数据
     * @returns
     */
    export function WrapGroup<T>(arrSource: T[], childCount: number, condFunc?: (data: T) => boolean, extraFunc?: (data: T) => any): Data[][] {
        if (!arrSource) return [];

        let list: Data[][] = [];

        let row = 0;
        let rank = 0;
        for (let i = 0, l = arrSource.length; i < l; ++i) {
            let v = arrSource[i];

            let pass = true;
            if (condFunc) {
                pass = condFunc(v);
            }
            if (!pass) continue;

            if (!list[row]) {
                list[row] = [];
            }
            if (list[row].length == childCount) {
                row++;
            }
            if (!list[row]) {
                list[row] = [];
            }

            let extra = void 0;
            if (extraFunc) {
                extra = extraFunc(v);
            }
            let data = new Data(rank++, v, extra);
            list[row].push(data);
        }

        return list;
    }


    /**
     * 列表项点击事件
     */
    export type FuncItemClick = (last: Node | null, curr: Node, data: Data, cmd?: string) => void;
}